import { useState, useEffect } from 'react'
import { View, Image, ScrollView } from '@tarojs/components'
import './index.scss'
import Taro, { useDidShow } from '@tarojs/taro'

// 定义账单数据类型
interface BillRecord {
  amount: string
  type: string | number
  selectedType: string
  remarks: string
  date: string
  selectedIcon: string
  id: string
}

const Category = () => {
  const STORAGE_KEY = 'bill_records'
  const [list, setList] = useState<BillRecord[]>([])
  const [refreshing, setRefreshing] = useState(false)
  const [monthBudget, setMonthBudget] = useState<string>('')

  // 主题：light | dark
  const [theme, setTheme] = useState<'light' | 'dark'>(() => {
    try {
      const cached = Taro.getStorageSync('app_theme') as 'light' | 'dark'
      return cached === 'dark' ? 'dark' : 'light'
    } catch {
      return 'light'
    }
  })

  const getMonthKey = () => {
    const now = new Date()
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
  }
  const BUDGET_STORAGE_KEY = (month: string) => `budget_${month}`

  // 组件加载时读取数据
  useEffect(() => {
    loadBillRecords()
    loadMonthBudget()
  }, [])

  useDidShow(() => {
    try {
      const cached = Taro.getStorageSync('app_theme') as 'light' | 'dark'
      setTheme(cached === 'dark' ? 'dark' : 'light')
    } catch {}
  })

  // 从本地存储加载账单记录
  const loadBillRecords = async () => {
    try {
      const data = await Taro.getStorage({ key: STORAGE_KEY })
      if (data.data) {
        const records = JSON.parse(data.data)
        // 按时间倒序排列（最新的在前）
        const sortedRecords = records.sort((a: BillRecord, b: BillRecord) => {
          return new Date(b.date).getTime() - new Date(a.date).getTime()
        })
        setList(sortedRecords)
        console.log('加载账单记录:', sortedRecords)
      }
    } catch (error) {
      console.log('暂无账单记录')
      setList([])
    }
  }

  const loadMonthBudget = async () => {
    try {
      const key = BUDGET_STORAGE_KEY(getMonthKey())
      const data = await Taro.getStorage({ key })
      if (data?.data !== undefined && data?.data !== null) {
        setMonthBudget(String(data.data))
      } else {
        setMonthBudget('')
      }
    } catch {
      setMonthBudget('')
    }
  }

  // 下拉刷新
  const onRefresh = async () => {
    setRefreshing(true)
    await loadBillRecords()
    setRefreshing(false)
    Taro.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1000
    })
  }

  // 计算本月支出和收入
  const calculateMonthTotal = () => {
    const now = new Date()
    const currentMonth = now.getMonth()
    const currentYear = now.getFullYear()
    
    let monthExpense = 0
    let monthIncome = 0
    
    list.forEach(record => {
      const recordDate = new Date(record.date)
      if (recordDate.getMonth() === currentMonth && recordDate.getFullYear() === currentYear) {
        const amount = parseFloat(record.amount)
        if (record.type === '1') { // 支出
          monthExpense += amount
        } else { // 收入
          monthIncome += amount
        }
      }
    })
    
    return { monthExpense, monthIncome }
  }

  const { monthExpense, monthIncome } = calculateMonthTotal()
  const budgetNum = parseFloat(monthBudget || '0') || 0
  const remain = budgetNum - monthExpense

  // 计算今日支出和收入
  const calculateTodayTotal = () => {
    const today = new Date().toLocaleDateString('zh-CN')
    
    let todayExpense = 0
    let todayIncome = 0
    
    list.forEach(record => {
      const recordDate = new Date(record.date).toLocaleDateString('zh-CN')
      if (recordDate === today) {
        const amount = parseFloat(record.amount)
        if (record.type === '1') { // 支出
          todayExpense += amount
        } else { // 收入
          todayIncome += amount
        }
      }
    })
    
    return { todayExpense, todayIncome }
  }

  const { todayExpense, todayIncome } = calculateTodayTotal()
  
  return (
    <View className={`overview-page ${theme === 'dark' ? 'theme-dark' : 'theme-light'}`}>
      <View className="overview-header">
        <View className="header-title">我的记账本</View>
      </View>

      <View className="overview-stats">
        <View className="stat-card">
          <View className="stat-label">本月支出</View>
          <View className="stat-value expense">¥{monthExpense.toFixed(2)}</View>
        </View>
        <View className="stat-card">
          <View className="stat-label">本月收入</View>
          <View className="stat-value income">¥{monthIncome.toFixed(2)}</View>
        </View>
      </View>

      {/* 本月预算 */}
      <View className="budget-card">
        <View className="budget-top">
          <View className="budget-title">本月预算</View>
          <View className="budget-amount">¥{budgetNum.toFixed(2)}</View>
        </View>
        <View className="budget-bottom">
          <View className="budget-item">
            <View className="label">已用</View>
            <View className="value expense">¥{monthExpense.toFixed(2)}</View>
          </View>
          <View className="budget-item">
            <View className="label">剩余</View>
            <View className={`value ${remain < 0 ? 'expense' : 'income'}`}>¥{remain.toFixed(2)}</View>
          </View>
        </View>
      </View>

      <View className="overview-today">
        <View className="today-item">
          <View className="today-label">今日支出</View>
          <View className="today-value expense">¥{todayExpense.toFixed(2)}</View>
        </View>
        <View className="today-item">
          <View className="today-label">今日收入</View>
          <View className="today-value income">¥{todayIncome.toFixed(2)}</View>
        </View>
      </View>

      <View className="overview-list-title">
        <View>账单明细</View>
        <View className="refresh-btn" onClick={onRefresh}>
          {refreshing ? '刷新中...' : '刷新'}
        </View>
      </View>

      <ScrollView
        scrollY
        className="overview-list"
        style={{ height: 'calc(100vh - 400px)' }}
      >
        {list.length === 0 ? (
          <View className="empty-state">暂无账单记录</View>
        ) : (
          list.map((item) => (
            <View key={item.id} className="list-item">
              <View className="item-left">
                <Image
                  src={item.selectedIcon}
                  className="item-icon"
                  mode="aspectFit"
                />
                <View className="item-info">
                  <View className="item-type">{item.selectedType}</View>
                  {item.remarks && (
                    <View className="item-remarks">{item.remarks}</View>
                  )}
                </View>
              </View>
              <View className="item-right">
                <View className={`item-amount ${item.type === '1' ? 'expense' : 'income'}`}>
                  {item.type === '1' ? '-' : '+'}¥{item.amount}
                </View>
                <View className="item-date">{item.date}</View>
              </View>
            </View>
          ))
        )}
      </ScrollView>
    </View>
  )
}

export default Category
